package com.zjitc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.config.AlipayConfig;
import com.express.config.ExpressAPI;
import com.express.config.KdniaoTrackQueryAPI;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.zjitc.model.CartItem;
import com.zjitc.model.Order;
import com.zjitc.model.OrderItem;
import com.zjitc.model.User;
import com.zjitc.service.CartService;
import com.zjitc.service.OrderService;
import com.zjitc.utils.UUIDUtils;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/15 17:01
 * @description:
 */
@Controller
@RequestMapping("/order")
public class OrderController {
  @Autowired
  public OrderService orderService;

  @Autowired
  public CartService cartService;

  @RequestMapping("/addList")
  public String addList(HttpSession session,Model model){
    User user= (User) session.getAttribute("users");
    Order order=new Order();
    order.setOid(UUIDUtils.getId());
    order.setOrdertime(new Date());
    double total= (double) session.getAttribute("total");
    order.setTotal(total);
    order.setState(0);
    List<CartItem> cartItems = cartService.findAll(user.getUid());
    for(CartItem cartItem:cartItems){
      OrderItem orderItem=new OrderItem();
      orderItem.setItemid(UUIDUtils.getId());
      orderItem.setCount(cartItem.getCount());
      orderItem.setSubtotal(cartItem.getTotal());
      orderItem.setPid(cartItem.getProduct().getPid());
      orderItem.setProduct(cartItem.getProduct());
      orderItem.setOid(order.getOid());
      order.getItems().add(orderItem);
    }
    order.setUid(user.getUid());
    orderService.add(order);
    model.addAttribute("order",order);
    cartService.clearCart(user.getUid());
    return "/jsp/order_info.jsp";
  }

  @RequestMapping("/findOrderList")
  public String findOrderList(
      @RequestParam(name = "pageNum",defaultValue = "1")Integer pageNum,
      HttpSession session,Model model){
    User user= (User) session.getAttribute("users");
    List<Order> order=orderService.findByUid(user.getUid(),pageNum);
    PageInfo<Order> pageInfo= new PageInfo<Order>(order);
    model.addAttribute("order",order);
    model.addAttribute("page",pageInfo);
    return "/jsp/order_list.jsp";
  }

  @RequestMapping("/deleteOrders")
  public String delete(@RequestParam(name = "oid")String oid){
        orderService.delete(oid);
        return "forward:/order/findOrderList.do";
  }

  @RequestMapping("/payForToOrderInfo")
  public String pay(@RequestParam(name = "oid")String oid,
      Model model){
    Order order=orderService.findByOid(oid);
    model.addAttribute("order",order);
    return "/jsp/order_info.jsp";
  }

  @RequestMapping("/payOrder")
  public String pay(@RequestParam(name = "oid")String oid){
    orderService.payForUpdateOid(oid);
    return "forward:/order/findOrderList.do";
  }

  @RequestMapping("/refund")
  public String refund(@RequestParam(name = "oid")String oid,
      Model model){
    Order order=orderService.findByOid(oid);
    model.addAttribute("order",order);
    return "/jsp/refund.jsp";
  }

  @RequestMapping("/refundOrder")
  public String refundOrder(@RequestParam(name = "oid")String oid,
      HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
    //获得初始化的AlipayClient
    AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

    //设置请求参数
    AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

    //商户订单号，商户网站订单系统中唯一订单号
    String out_trade_no = new String(request.getParameter("WIDTRout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
    //支付宝交易号
    String trade_no = new String(request.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
    //请二选一设置
    //需要退款的金额，该金额不能大于订单金额，必填
    String refund_amount = new String(request.getParameter("WIDTRrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
    //退款的原因说明
    String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
    //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
    String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");

    alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        + "\"trade_no\":\""+ trade_no +"\","
        + "\"refund_amount\":\""+ refund_amount +"\","
        + "\"refund_reason\":\""+ refund_reason +"\","
        + "\"out_request_no\":\""+ out_request_no +"\"}");

    //请求
    String result = alipayClient.execute(alipayRequest).getBody();
    System.out.println(result);
    String str=oid;
    String[] arr=str.split(",");
    List list=java.util.Arrays.asList(arr);
    String o = String.valueOf(list.get(0));
    orderService.updateRefund(o);
    return "forward:/order/findOrderList.do";
  }

  @RequestMapping("/searchExpress")
  public String search(@RequestParam(name = "oid")String oid,Model model) throws Exception {
    KdniaoTrackQueryAPI api=new KdniaoTrackQueryAPI();
    Order order = orderService.findByOid(oid);
    String result=api.getOrderTracesByJson("YD",order.getExpress());
    Gson gson=new Gson();
    ExpressAPI expressAPI=gson.fromJson(result,ExpressAPI.class);
    if(expressAPI.isSuccess()){
      model.addAttribute("express",expressAPI);
      return "/jsp/express.jsp";
    }
    return null;
  }
}
